宣告會提升但賦值不會


test()

const test = function() {
  console.log('test')
}
// Uncaught ReferenceError: Cannot access 'test' before initialization

在 function 裡的 a 提升

宣告變數會提升,賦值不會

var a = 'global'

function test() {
  console.log(a)
  var a = '10'
}

test()
// a is undelined

function 的優先度高於宣告變數

function test() {
  console.log(a)
  function a() {}
  var a = 'local'
}

test() // f a() {}

同時宣告兩個一樣的 function,後者勝

var a = 'global'

function test() {
  a()
  function a() {
    console.log(1)
  }
  function a() {
    console.log(2)
  }
  var a = 'local'
}

test() // 2

hoisting 提升的順序

  1. function
  2. arguments (參數)
  3. var

參考資源


#程式導師實驗計畫第四期 #前端 #hoisting







Related Posts

如何不使用 create-react-app 自己打造應用程式

如何不使用 create-react-app 自己打造應用程式

來學 React 吧之四_Class component 介紹及與 Function component 的差異

來學 React 吧之四_Class component 介紹及與 Function component 的差異

聽說有隻鯨魚叫Docker?

聽說有隻鯨魚叫Docker?


Comments